<!-- 新增和修改 -->
<template>
  <div class="app-container">
    <Edialog
      :outershow="outershow"
      :title="title"
      @saveFn="saveFn"
      @close="closeFn"
      :saveClick="true"
      width="50%"
    >
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form
            ref="form"
            :model="form"
            label-width="auto"
            :rules="rules"
            inline
          >
            <el-row>
              <el-col :span="12">
                <el-form-item
                  label="模板名称"
                  prop="templateName"
                  v-if="form.templateName"
                >
                  <div>{{ form.templateName }}</div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="科目标识"
                  prop="subjectSign"
                  class="subjectSign"
                >
                  <el-select
                    v-if="type == 'add'"
                    v-model="form.subjectSign"
                    @focus="templatechooseNoTreeFn"
                  >
                  </el-select>
                  <div v-else>{{ form.subjectSign }}</div>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item
                  label="科目行名称"
                  prop="subjectRowName"
                  v-if="form.subjectRowName"
                >
                  {{ form.subjectRowName }}
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="科目列名称"
                  prop="subjectColName"
                  v-if="form.subjectColName"
                >
                  {{ form.subjectColName }}
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-form-item
                label="方法公式"
                prop="formula"
                class="formula"
                style="width: 100%; flex-wrap: wrap"
              >
                <el-tabs
                  tab-position="left"
                  :before-leave="beforeLeave"
                  v-model="activeName"
                >
                  <el-tab-pane label="数据来源" name="data">
                    <!-- 多行输入 -->
                    <el-input type="textarea" v-model="form.formula"
                  /></el-tab-pane>
                  <el-tab-pane label="函数" name="formula">
                    <span slot="label">
                      <img
                        width="20"
                        height="20"
                        src="@/assets/icons/fx.png"
                        alt=""
                        style="margin-right: 5px"
                        @click="fxchooseFn"
                      /> </span
                  ></el-tab-pane>
                  <el-tab-pane label="模板" name="template">
                    <span slot="label">
                      <img
                        width="20"
                        height="20"
                        src="@/assets/icons/temp.png"
                        alt=""
                        @click="templatechooseFn" /></span
                  ></el-tab-pane>
                </el-tabs>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item
                label="动态公式"
                v-if="form.isDynamic == '动态'"
                style="width: 100%"
              >
                <!-- 多行输入 -->
                <el-input type="textarea" v-model="form.asyncFormula" />
              </el-form-item>
            </el-row>
          </el-form>
        </el-col>
      </el-row>
    </Edialog>
    <subject_choose @rowdblclick="rowdblclick" ref="subject_choose" />
    <subject_choose_noTree
      @rowdblclick="noTreeRowdblclick"
      ref="subject_choose_noTree"
    />
    <fx_choose ref="fx_choose" @rowdbckick="fxrowdbckick" />
  </div>
</template>

<script>
import {
  indexToCoord,
  getNonEmptyMergedCells,
  coordToIndex,
  getColumnTitleValues,
  getRowTitleValues,
  updateCellAttributes,
} from "@/utils/spreadsheet.js";
import subject_choose from "@/components/Xspreadsheet/subject_choose.vue";
import subject_choose_noTree from "@/components/Xspreadsheet/subject__choose_noTree.vue";
import fx_choose from "@/components/Xspreadsheet/fx_choose.vue";
import SpreadSheet from "@/components/Xspreadsheet/SpreadSheet.vue";
import Edialog from "@/components/Edialog";
import {
  putBsFormulaApi,
  postBsFormulaApi,
  BsFormulaByIdApi,
} from "@/api/formulaConfig";
import { BsSubjectByIdApi } from "@/api/subjectConfig";
import { BsTemplateByIdApi } from "@/api/templateManage";
export default {
  data() {
    return {
      activeName: "data",
      rules: {
        subjectSign: [{ required: true, message: "请选择", trigger: "blur" }],
        formula: [
          { required: true, message: "请输入", trigger: "blur" },
          { validator: this.validateFormula, trigger: "change" },
        ],
      },
      tableData: [],
      tableLoading: false,
      tableHeight: "calc(60vh - 186px)",

      file: null,
      ColumnCount: 30,
      RowCount: 100,
      headers: [],
      records: [],

      outershow: false,
      type: "add",
      title: "新增",
      form: {
        col: "",
        row: "",
        address: "",
        sAddress: "",
        eAddress: "",
        text: "",
        formula: "=",
        asyncFormula: "=",
        subjectCode: "",
        subjectSign: "",
        subjectColName: "",
        subjectRowName: "",
        subjectName: "",
      },
      spreadsheetData: [],
    };
  },
  components: {
    Edialog,
    SpreadSheet,
    subject_choose,
    fx_choose,
    subject_choose_noTree,
  },
  methods: {
    validateFormula(rule, value, callback) {
      if (value === "=") {
        callback(new Error("请输入正确的公式"));
      } else {
        callback();
      }
    },
    //函数模板选择器回调：回显公式
    rowdblclick(row) {
      console.log("有树", row);
      // this.form.templateCode = row.templateCode;
      // this.form.excelJson = row.excelJson;
      //如果 this.form.text包括等号，则直接添加函数,否则在最前面加上等号
      if (this.form.formula && this.form.formula.includes("=")) {
        this.form.formula =
          this.form.formula += `'${row.templateCode}'!${row.subjectSign}`;
      } else {
        this.form.formula =
          this.form.formula = `='${row.templateCode}'!${row.subjectSign}`;
      }
    },
    //函数选择器回调
    fxrowdbckick(row) {
      //如果 this.form.text包括等号，则直接添加函数,否则在最前面加上等号
      if (this.form.formula && this.form.formula.includes("=")) {
        this.form.formula = this.form.formula += row.funcCode;
      } else {
        this.form.formula = this.form.formula = "=" + row.funcCode;
      }
    },
    //无树模板选择器回调的是新增时的选中模板中的科目信息
    noTreeRowdblclick(row) {
      console.log("无树", row);
      this.form.subjectCode = row.subjectCode;
      this.form.subjectName = row.subjectRowName + " - " + row.subjectColName;
      this.form.subjectRowName = row.subjectRowName;
      this.form.subjectColName = row.subjectColName;
      this.form.isDynamic = row.isDynamic;
      this.form.subjectId = row.id;
      // this.form.templateCode = row.templateCode;
      // this.form.excelJson = row.excelJson;
    },
    templatechooseFn() {
      this.$refs.subject_choose.manufacturerOpen();
    },
    templatechooseNoTreeFn() {
      this.$refs.subject_choose_noTree.manufacturerOpen({
        templateId: this.currentTemplateId,
      });
    },
    fxchooseFn() {
      this.$refs.fx_choose.open();
    },
    beforeLeave(activeName, oldActiveName) {
      if (activeName === "data") {
      } else if (this.activeName == "template") {
        // this.templatechooseFn();
        return false;
      } else if (this.activeName == "fn") {
        return false;
      } else {
        return false;
      }
    },

    //外部打开弹窗
    async openFn(type, row) {
      this.outershow = true;
      this.type = type;
      this.currentTemplateId = row.templateId;
      let res = await BsTemplateByIdApi(row.templateId);
      if (res.data && res.data.bcode == 0) {
        this.spreadsheetData = JSON.parse(res.data.bdata.excelJson);
        console.log(
          "res.data",
          this.spreadsheetData,
          JSON.parse(row.excelJson)
        );
        this.form.templateCode = res.data.bdata.templateCode;
        // this.form.excelJson = res.data.bdata.excelJson;
      } else {
        this.spreadsheetData = JSON.parse(row.excelJson);
      }
      if (type === "edit") {
        this.title = "修改";
        //下面为目前废弃逻辑，暂时注释
        // let subjectDetail = {
        //   subjectCode: "",
        //   subjectColName: "",
        //   subjectRowName: "",
        //   templateCode: "",
        //   templateName: "",
        // };
        // let res1 = await BsFormulaByIdApi(row.id);
        // console.log("公式详情", res1.data.bdata);
        // if (res1.data && res1.data.bcode == 0) {
        //   let res2 = await BsSubjectByIdApi(res1.data.bdata.subjectId);
        //   if (res2.data && res2.data.bcode == 0) {
        //     console.log("科目详情", res2.data.bdata);
        //     subjectDetail.subjectCode = res2.data.bdata.subjectCode;
        //     subjectDetail.subjectColName = res2.data.bdata.subjectColName;
        //     subjectDetail.subjectRowName = res2.data.bdata.subjectRowName;
        //     subjectDetail.templateCode = row.templateCode;
        //     subjectDetail.templateName = row.templateName;
        //   }
        //   this.form = Object.assign(res1.data.bdata, subjectDetail);
        // }

        this.form = Object.assign({}, row);
        console.log("修改form", this.form);
      } else {
        this.form.subjectRowName = "";
        this.form.subjectColName = "";
        setTimeout(() => {
          this.$nextTick(() => {
            this.$refs.form.resetFields();
          });
        });

        this.title = "新增";
      }
    },
    saveFn() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.form.id) {
            console.log("修改form", this.form);
            //给excelJson添加表单中设置的数据属性
            let { rowIndex, colIndex } = coordToIndex(this.form.subjectCode);
            let excelJson = this.$cloneDeep(this.spreadsheetData);
            updateCellAttributes(
              rowIndex,
              colIndex,
              {
                formula: this.form.formula,
                asyncFormula: this.form.asyncFormula,
                // text: this.form.formula,
              },
              excelJson
            );
            this.form.excelJson = JSON.stringify(excelJson);
            console.log("添加后的excelJson", excelJson);

            let obj = {
              id: this.form.id,
              formula: this.form.formula,
              subjectId: this.form.subjectId,
              asyncFormula: this.form.asyncFormula,
              templateCode: this.form.templateCode,
              excelJson: this.form.excelJson,
            };
            console.log("修改", obj);
            postBsFormulaApi(obj).then((res) => {
              if (res.data && res.data.bcode == 0) {
                this.$message.success("修改成功");
                this.closeFn();
                this.$emit("refresh");
              }
            });
          } else {
            //给excelJson添加表单中设置的数据属性
            let { rowIndex, colIndex } = coordToIndex(this.form.subjectCode);
            let excelJson = this.$cloneDeep(this.spreadsheetData);
            updateCellAttributes(
              rowIndex,
              colIndex,
              {
                formula: this.form.formula,
                asyncFormula: this.form.asyncFormula,
                // text: this.form.formula,
              },
              excelJson
            );
            this.form.excelJson = JSON.stringify(excelJson);
            let obj = {
              formula: this.form.formula,
              subjectId: this.form.subjectId,
              asyncFormula: this.form.asyncFormula,
              templateCode: this.form.templateCode,
              excelJson: this.form.excelJson,
            };
            console.log("新增", obj);
            putBsFormulaApi(obj).then((res) => {
              if (res.data && res.data.bcode == 0) {
                this.$message.success("新增成功");
                this.closeFn();
                this.$emit("refresh");
              }
            });
          }
        }
      });
    },
    closeFn() {
      this.$refs.form.resetFields();
      this.outershow = false;
    },
  },
};
</script>
<style lang="scss" scoped>
.el-select {
  width: 100%;
}
.el-form-item {
  // width: 45%;
  display: flex;
}
::v-deep .el-form-item__content {
  // width: 90% !important;
  flex: 1;
}
.ellipsis_text {
  width: 200px; /* 或者你希望的固定宽度 */
  white-space: nowrap; /* 防止文本换行 */
  overflow: hidden; /* 隐藏超出容器的文本 */
  text-overflow: ellipsis; /* 使用省略号表示超出容器的文本 */
}
.formula {
  ::v-deep .el-form-item__label-wrap {
    width: 100%;
  }
  ::v-deep .el-textarea__inner {
    height: 13vh;
  }
  ::v-deep .el-form-item__error {
    left: 108px;
  }
}
.subjectSign {
  ::v-deep .el-select-dropdown {
    display: none !important;
  }
  ::v-deep .el-popper {
    display: none !important;
  }
}
</style>
